package com.qys.livesMall.shop.service.impl;


import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.qys.livesMall.app.user.model.entity.H2AppUser;
import com.qys.livesMall.app.user.service.IH2AppUserService;
import com.qys.livesMall.common.constants.Constants;
import com.qys.livesMall.common.exception.QysException;
import com.qys.livesMall.common.message.MessageServer;
import com.qys.livesMall.common.result.R;
import com.qys.livesMall.common.utils.bean.BeanProUtils;
import com.qys.livesMall.framework.utils.SecurityUtils;
import com.qys.livesMall.shop.constants.ShopConstant;
import com.qys.livesMall.shop.dao.H2ShopBaseDao;
import com.qys.livesMall.shop.dao.H2ShopLevelDao;
import com.qys.livesMall.shop.dao.H2ShopLevelRecordDao;
import com.qys.livesMall.shop.enums.ShopMessageEnum;
import com.qys.livesMall.shop.mapper.H2ShopLevelMapper;
import com.qys.livesMall.shop.modal.dto.shop.level.ShopLevelSaveDTO;
import com.qys.livesMall.shop.modal.entity.H2ShopBase;
import com.qys.livesMall.shop.modal.entity.H2ShopLevel;
import com.qys.livesMall.shop.modal.entity.H2ShopLevelRecord;
import com.qys.livesMall.shop.modal.vo.ShopLevelVO;
import com.qys.livesMall.shop.service.H2ShopLevelService;

import com.qys.livesMall.shop.service.ShopIncomeConfigService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author wzy
 * @since 2023-04-05
 */
@Slf4j
@Service
public class H2ShopLevelServiceImpl implements H2ShopLevelService {

    @Autowired
    private H2ShopBaseDao shopBaseDao;
    @Autowired
    private IH2AppUserService userService;

    @Autowired
    private H2ShopLevelDao shopLevelDao;

    @Autowired
    private H2ShopLevelRecordDao shopLevelRecordDao;

    @Autowired
    private MessageServer messageServer;

    @Autowired
    private H2ShopLevelMapper h2ShopLevelMapper;

    @Autowired
    private ShopIncomeConfigService shopIncomeConfigService;

    @Override
    public List<ShopLevelVO> list() {
        List<H2ShopLevel> levels = shopLevelDao.list();
        return BeanProUtils.copyListProperties(levels, ShopLevelVO::new);
    }

    @Override
    public void saveOrUpdate(ShopLevelSaveDTO saveDTO) {
        H2ShopLevel level = new H2ShopLevel();
        //新增
        if (null == saveDTO.getId()) {
            if (shopLevelDao.count(Wrappers.<H2ShopLevel>lambdaQuery().eq(H2ShopLevel::getLevel, saveDTO.getLevel())) > 0) {
                throw new QysException(ShopMessageEnum.SHOP_LEVEL_IS_EXIST);
            }
            level.setActivityFlag((byte) 1);
            level.setSellTaskFlag((byte) 1);
            level.setCashBeforeDelivery((byte) 1);
            level.setDeliveryBeforeCash((byte) 1);
            level.setCreateBy(SecurityUtils.getUsername());
            level.setCreateTime(LocalDateTime.now());
        } else {
            level = shopLevelDao.getById(saveDTO.getId());
            if (level == null) {
                throw new QysException("ID传错了或此条数据不存在");
            }
            //检查是否存在相同的下一级
            H2ShopLevel levelTemp = shopLevelDao.getUpOneLevel(saveDTO.getNextLevel());
            if (levelTemp != null) {
                if (!Objects.equals(level.getId(), levelTemp.getId())) {
                    throw new QysException(ShopMessageEnum.CANNOT_HAVE_TWO_LEVELS);
                }
            }
            level.setUpdateBy(SecurityUtils.getUsername());
            level.setUpdateTime(LocalDateTime.now());
        }
        BeanUtils.copyProperties(saveDTO, level);
        shopIncomeConfigService.checkPlatformRatio(level.getPlatformRatio());
        shopLevelDao.saveOrUpdate(level);

    }

    @Override
    public R<?> delete(Integer id) {
        H2ShopLevel level = shopLevelDao.getById(id);
        if (level == null) {
            return messageServer.failMsg(ShopMessageEnum.SHOP_BASE_LEVEL_ERROR);
        }
        //检查是否有上一级
        H2ShopLevel upLevel = shopLevelDao.getUpOneLevel(id);
        if (upLevel != null) {
            return messageServer.failMsg(ShopMessageEnum.SHOP_EXIST_UP_LEVEL);
        }
        //检查是否被使用
        if (shopBaseDao.existByLevel(id)) {
            return messageServer.failMsg(ShopMessageEnum.SHOP_LEVEL_USE);
        }
        shopLevelDao.removeById(level);
        return R.ok();
    }

    @Override
    public void upgradeTask(Long userId) {
        H2AppUser user = userService.getById(userId);
        H2AppUser parentUser = userService.getById(user.getSuperior());
        //查询上级用户
        if (parentUser == null) {
            log.info("用户:【{}】,无上级用户", userId);
            return;
        }
        H2ShopBase shop = shopBaseDao.getByUserId(Long.valueOf(parentUser.getId()));
        if (shop == null) {
            log.info("用户:【{}】,未开店铺", parentUser.getId());
            return;
        }

        if (Objects.equals(shop.getStatus(), ShopConstant.ShopStatus.IN_BUSINESS)) {
            log.info("用户:【{}】,店铺状态不正常", parentUser.getId());
            return;
        }
        H2ShopLevel level = shopLevelDao.getUpOneLevel(shop.getShopLevelId());
        if (level == null) {
            return;
        }
        List<String> userIds =          userService.list(Wrappers.<H2AppUser>query()
                .eq("superior",parentUser.getId())
                .eq("deleted", 0)).stream().map(H2AppUser::getId).collect(Collectors.toList());
        List<Long> ids=userIds.stream().mapToLong(Long::parseLong).boxed().collect(Collectors.toList());
        long count = shopBaseDao.getUserInviteShopCount(ids);

        //升级需要下级店铺数量 -1减去当前店铺未升级


        log.info("父级用户:【{}】,升级店铺等级需要的下级人数为【{}】,满足人数为【{}】,{}升级条件!!!",
                user.getId(),
                level.getUpgradeConditionNum(),
                count,
                count >= level.getUpgradeConditionNum() ? "满足" : "不满足"
        );
        if (count >= level.getUpgradeConditionNum()) {//上级满足升级条件
            H2ShopLevelRecord record = shopLevelRecordDao.getRecord(Long.valueOf(parentUser.getId()), shop.getId(), level.getId());
            if (record == null) {
                //增加升级记录
                record = new H2ShopLevelRecord();
                record.setShopId(shop.getId());
                record.setUserId(parentUser.getId());
                record.setShopLevelId(level.getId());
                record.setEarnestMoney(level.getEarnestMoney());
                record.setPayMoneyFlag(Constants.YesNoInt.NO);
                record.setReturnMoneyFlag(Constants.YesNoInt.NO);
                shopLevelRecordDao.save(record);
            }

        }

    }

    /**
     * 判断等级是否允许操作
     *
     * @param shopLevelId
     * @return 1:先付后货  2:先货后付  3:是否允许参加平台活动  4:是否允许发起任务
     */
    @Override
    public boolean allowOperation(Integer shopLevelId, Integer type) {
        H2ShopLevel shopLevel = shopLevelDao.getById(shopLevelId);
        if (shopLevel == null) {
            return true;
        }
        byte flag = 0;
        if (type == 1) {
            flag = shopLevel.getCashBeforeDelivery();
        }

        if (type == 2) {
            flag = shopLevel.getDeliveryBeforeCash();
        }
        if (type == 3) {
            flag = shopLevel.getActivityFlag();
        }
        if (type == 4) {
            flag = shopLevel.getSellTaskFlag();
        }
        return flag == 1;
    }

    @Override
    public H2ShopLevel getById(Integer id) {
        return shopLevelDao.getById(id);
    }

    @Override
    public BigDecimal getMaxPlatformRatio() {
        return h2ShopLevelMapper.getMaxPlatformRatio();
    }

    @Override
    public BigDecimal getUpgradeReward(Integer minLevel,Integer maxLevel){
        return h2ShopLevelMapper.getUpgradeReward(minLevel,maxLevel);
    }

    public Integer getByUpgradeConditionNum(long num){
        return h2ShopLevelMapper.getByUpgradeConditionNum(num);
    }
}
